package io.github.wslxm.springbootplus2.manage.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.wslxm.springbootplus2.core.base.model.BasePage;
import io.github.wslxm.springbootplus2.core.base.service.impl.BaseServiceImpl;
import io.github.wslxm.springbootplus2.core.enums.BaseDic;
import io.github.wslxm.springbootplus2.core.utils.XjBeanUtil;
import io.github.wslxm.springbootplus2.core.utils.tree.XjTreeUtil;
import io.github.wslxm.springbootplus2.manage.sys.dao.SysRoleDao;
import io.github.wslxm.springbootplus2.manage.sys.dao.SysRoleMenuDao;
import io.github.wslxm.springbootplus2.manage.sys.mapper.SysMenuMapper;
import io.github.wslxm.springbootplus2.manage.sys.model.dto.SysMenuDTO;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysMenu;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysRole;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysRoleMenu;
import io.github.wslxm.springbootplus2.manage.sys.model.query.SysMenuQuery;
import io.github.wslxm.springbootplus2.manage.sys.model.query.next.SysMenuTreeQuery;
import io.github.wslxm.springbootplus2.manage.sys.model.vo.SysMenuVO;
import io.github.wslxm.springbootplus2.manage.sys.service.SysMenuService;
import io.github.wslxm.springbootplus2.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 菜单
 *
 * @author wangsong
 */
@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysRoleMenuDao roleMenuDao;

    @Override
    public List<SysMenuVO> tree(SysMenuTreeQuery query) {
        // 获取当前登录用户的 菜单ids
        String userId = query.getIsLoginUser() != null && query.getIsLoginUser() ? JwtUtil.getJwtUser(request).getUserId() : null;
        List<SysRoleMenu> menus = roleMenuDao.findMenuIdsByUserId(userId, 0);
        List<String> menuIds = null;
        if (menus.size() > 0) {
            menuIds = menus.stream().map(SysRoleMenu::getMenuId).toList();
        }
        // 查询
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<SysMenu>()
                .orderByAsc(SysMenu::getSort)
                .orderByDesc(SysMenu::getCreateTime);
        queryWrapper.eq(StringUtils.isNotBlank(query.getPid()), SysMenu::getPid, query.getPid());
        queryWrapper.le(query.getRoot() != null, SysMenu::getRoot, query.getRoot());
        queryWrapper.eq(query.getDisable() != null, SysMenu::getDisable, query.getDisable());
        queryWrapper.in(menuIds != null, SysMenu::getId, menuIds);
        List<SysMenu> list = this.list(queryWrapper);
        List<SysMenuVO> vos = XjBeanUtil.listVo(list, SysMenuVO.class);
        // 返回
        String pid = StringUtils.isNotBlank(query.getPid()) ? query.getPid() : "0";
        return XjTreeUtil.nextTree(vos, pid).getChildren();
    }

    @Override
    public BasePage<SysMenuVO> findPage(SysMenuQuery query) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<SysMenu>()
                .orderByAsc(SysMenu::getSort)
                .orderByDesc(SysMenu::getCreateTime);
        queryWrapper.eq(StringUtils.isNotBlank(query.getPid()), SysMenu::getPid, query.getPid());
        queryWrapper.likeRight(StringUtils.isNotBlank(query.getName()), SysMenu::getName, query.getName());
        queryWrapper.eq(query.getRoot() != null, SysMenu::getRoot, query.getRoot());
        queryWrapper.eq(query.getDisable() != null, SysMenu::getDisable, query.getDisable());
        Page<SysMenu> page = this.page(new Page<>(query.getCurrent(), query.getSize()), queryWrapper);
        return XjBeanUtil.pageVo(page, SysMenuVO.class);
    }

    @Override
    public SysMenuVO findId(String id) {
        return XjBeanUtil.convert(this.getById(id), SysMenuVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insert(SysMenuDTO dto) {
        SysMenu adminMenu = dto.convert(SysMenu.class);
        adminMenu.setCreateUser(JwtUtil.getJwtUser(request).getUserId());
        this.save(adminMenu);

        // 添加菜单给超管默认分配该菜单
        SysRole sysRole = sysRoleDao.findSuperManage();
        roleMenuDao.addRoleMenu(sysRole.getId(), adminMenu.getId());
        return adminMenu.getId();
    }


    @Override
    public boolean upd(String id, SysMenuDTO dto) {
        // 修改当前数据
        SysMenu entity = dto.convert(SysMenu.class);
        entity.setId(id);
        return this.updateById(entity);
    }

    @Override
    public boolean updPid(String id, String pid) {
        // 把顶级菜单 变更到其他目录/菜单下
        SysMenu menu = this.getById(id);
        menu.setPid(pid);
        if (menu.getRoot().equals(BaseDic.MenuRoot.V1.getValue())) {
            menu.setRoot(BaseDic.MenuRoot.V2.getValue());
        }
        return this.updateById(menu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> del(String id) {
        // 查询
        List<SysMenu> list = this.list();
        List<SysMenuVO> menuVos = XjBeanUtil.listVo(list, SysMenuVO.class);
        //
        List<String> menuIds = XjTreeUtil.getNextIds(menuVos, id);
        menuIds.add(id);
        // 删除菜单
        this.removeByIds(menuIds);
        // 删除角色菜单关联数据
        roleMenuDao.delByMenuIds(menuIds);
        return menuIds;
    }
}